/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.zjhcsoft.komm;

import java.security.acl.Group;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.Install;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.annotations.Startup;
import org.jboss.seam.annotations.intercept.BypassInterceptors;
import org.jboss.seam.security.Identity;
import org.jboss.seam.security.SimpleGroup;
import org.jboss.seam.security.SimplePrincipal;
import static org.jboss.seam.annotations.Install.APPLICATION;

/**
 *
 * @author zjhc
 */
@Name("org.jboss.seam.security.identity")
@Scope(ScopeType.SESSION)
@Install(precedence = APPLICATION)
@BypassInterceptors
@Startup
public class ExtendedIdentity extends Identity {

    public static final String PERMISSION_GROUP = "Permisions";

    @Override
    public void checkPermission(String arg0, String arg1, Object... arg2) {
        super.checkPermission(arg0, arg1, arg2);
    }

    @Override
    public void checkRestriction(String arg0) {
        super.checkRestriction(arg0);
    }

    @Override
    public boolean hasPermission(String target, String action, Object... arg2) {
        if (!securityEnabled) {
            return true;
        }
        isLoggedIn(true);
        String permission = target + ":" + action;
        for (Group sg : getSubject().getPrincipals(Group.class)) {
            if (PERMISSION_GROUP.equals(sg.getName())) {
                return sg.isMember(new SimplePrincipal(permission));
            }
        }
        return false;
    }

    /**
     * Adds a role to the user's subject, and their security context
     * 
     * @param role The name of the role to add
     */
    public boolean addPermission(String target, String action) {
        if (target == null || "".equals(target)) {
            return false;
        }
        String permission = target + ":" + action;

        for (Group sg : getSubject().getPrincipals(Group.class)) {
            if (PERMISSION_GROUP.equals(sg.getName())) {
                return sg.addMember(new SimplePrincipal(permission));
            }
        }
        SimpleGroup roleGroup = new SimpleGroup(PERMISSION_GROUP);
        roleGroup.addMember(new SimplePrincipal(permission));

        getSubject().getPrincipals().add(roleGroup);
        return true;
    }
}
